<template>
  <div class="price-display">
    <!-- A区域：货币显示 -->
    <div class="currency-section">
      <!-- 主要余额显示 -->
      <div class="main-balance">
        <div class="balance-header">
          <h2 class="balance-title">{{ $t('priceDisplay.totalAssets') }}</h2>
          <div class="balance-refresh" @click="refreshData">
            <el-icon :class="{ 'rotate': isLoading }">
              <Refresh />
            </el-icon>
          </div>
        </div>
        
        <div class="balance-amount">
          <template v-if="isWalletLoading">
            <span class="currency-symbol">₩</span>
            <span class="amount loading">{{ $t('priceDisplay.loading') }}...</span>
          </template>
          <template v-else-if="!walletDataAvailable">
            <span class="currency-symbol">₩</span>
            <span class="amount error">{{ $t('priceDisplay.dataUnavailable') }}</span>
          </template>
          <template v-else>
            <span class="currency-symbol">₩</span>
            <span class="amount">{{ formatNumber(totalBalance) }}</span>
          </template>
        </div>

        <div class="balance-change" :class="changeColorClass" v-if="walletDataAvailable">
          <span class="change-icon">{{ changeIcon }}</span>
          <span class="change-amount">{{ formatKRW(Math.abs(dayChange)) }}</span>
          <span class="change-percentage">({{ formatPercentage(dayChangeRate) }})</span>
        </div>

        <div v-else-if="!isWalletLoading" class="balance-error">
          <el-button type="text" @click="updateWalletData" class="retry-button">
            <el-icon><Refresh /></el-icon>
            {{ $t('priceDisplay.retryWalletData') }}
          </el-button>
        </div>

        <!-- 快捷操作按钮 -->
        <div class="balance-actions">
          <el-button class="action-button deposit-button" @click="handleDeposit">
            <Icon icon="mdi:wallet-plus" width="20" height="20" />
            <span>{{ $t('navigation.deposit') }}</span>
          </el-button>
          <el-button class="action-button withdraw-button" @click="handleWithdraw">
            <Icon icon="mdi:cash-minus" width="20" height="20" />
            <span>{{ $t('navigation.withdraw') }}</span>
          </el-button>
        </div>
      </div>

      <!-- NEAR 协议锁定数量信息 -->
      <div class="near-protocol-section">
        <div class="near-header">
          <div class="protocol-info">
            <div class="near-logo">
              <NearLogo :size="28" />
            </div>
            <div class="protocol-details">
              <h3 class="protocol-title">{{ $t('priceDisplay.nearProtocolTitle') }}</h3>
              <div class="upbit-price">
                <span class="exchange-label">{{ $t('priceDisplay.upbitRealtime') }}</span>
                <template v-if="isPriceLoading">
                  <span class="price-loading">{{ $t('priceDisplay.loading') }}...</span>
                </template>
                <template v-else-if="!priceDataAvailable">
                  <span class="price-error">{{ $t('priceDisplay.priceUnavailable') }}</span>
                  <el-button type="text" size="small" @click="updatePriceData">
                    {{ $t('priceDisplay.retry') }}
                  </el-button>
                </template>
                <template v-else>
                  <span class="price-value">{{ formatKRW(nearPrice) }}</span>
                  <span class="price-change" :class="nearPriceChangeClass">
                    {{ nearPriceChange > 0 ? '+' : '' }}{{ formatPercentage(nearPriceChangeRate) }}
                  </span>
                  <div class="live-indicator">
                    <div class="live-dot"></div>
                    <span class="live-text">{{ $t('priceDisplay.live') }}</span>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>
        
        <!-- NEAR 锁定数量详情 -->
        <div class="near-locked-details">
          <div class="locked-summary">
            <div class="summary-item main-locked">
              <div class="item-header">
                <span class="item-title">{{ $t('priceDisplay.totalHolding') }}</span>
                <span class="item-amount">{{ formatTokenAmount(totalNearHolding, 'NEAR') }}</span>
              </div>
              <div class="item-value-krw">{{ formatKRW(nearTotalValue) }}</div>
            </div>
          </div>

          <div class="locked-breakdown">
            <div class="breakdown-item rewards">
              <div class="breakdown-label">
                <span class="label-text">{{ $t('priceDisplay.freeHolding') }}</span>
                <span class="label-icon">💰</span>
              </div>
              <div class="breakdown-values">
                <span class="token-amount">{{ formatTokenAmount(freeHoldingNear, 'NEAR') }}</span>
                <span class="krw-amount">{{ formatKRW(freeHoldingKrw) }}</span>
              </div>
            </div>

            <div class="breakdown-item locked">
              <div class="breakdown-label">
                <span class="label-text">{{ $t('priceDisplay.stakingLocked') }}</span>
                <span class="label-icon">🔒</span>
              </div>
              <div class="breakdown-values">
                <span class="token-amount">{{ formatTokenAmount(nearStaked, 'NEAR') }}</span>
                <span class="krw-amount">{{ formatKRW(nearStaked * nearPrice) }}</span>
              </div>
            </div>

            <div class="breakdown-item rewards">
              <div class="breakdown-label">
                <span class="label-text">{{ $t('priceDisplay.stakingRewards') }}</span>
                <span class="label-icon">⭐</span>
              </div>
              <div class="breakdown-values">
                <span class="token-amount">{{ formatTokenAmount(totalRewardsNear, 'NEAR') }}</span>
                <span class="krw-amount">{{ formatKRW(totalRewardsValue) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Refresh } from '@element-plus/icons-vue'
import { Icon } from '@iconify/vue'
import { useI18n } from 'vue-i18n'
import { walletApiService } from '@/services/walletApi'

const { t: $t } = useI18n()
const router = useRouter()
import { formatKRW, formatNumber, formatPercentage, formatTokenAmount } from '@/utils/currency'
import NearLogo from '@/components/Common/NearLogo.vue'

// 加载状态
const isLoading = ref(false)
const isPriceLoading = ref(false)
const isWalletLoading = ref(false)
const isAssetLoading = ref(false)

// 价格数据
const nearPrice = ref(0)
const nearPriceChange = ref(0)
const nearPriceChangeRate = ref(0)
const priceDataAvailable = ref(false)

// 钱包数据
const ledgerNearBalance = ref(0) // 장부 기준 NEAR 총량
const nearStaked = ref(0) // 장부 기준 잠금 NEAR
const totalRewardsNear = ref(0) // 누적质押收益NEAR
const totalRewardsValue = ref(0) // 누적质押收益KRW
const cumulativeRewardsNear = ref(0) // 누적质押收益NEAR（展示用）
const cumulativeRewardsValue = ref(0) // 누적质押收益KRW（展示用）
const freeHoldingNear = ref(0) // 장부 기준 자유 보유 NEAR
const totalBalance = ref(0) // 장부 기준총액（KRW）
const immediateBalance = ref(0) // 可即时使用KRW
const frozenBalance = ref(0) // 冻结KRW
const dayChange = ref(0)
const dayChangeRate = ref(0)
const walletDataAvailable = ref(false)

// 资产数据
const assetDataAvailable = ref(false)

let priceUpdateInterval: number | null = null

const totalNearHolding = computed(() => ledgerNearBalance.value)
const nearTotalValue = computed(() => totalBalance.value)
const freeHoldingKrw = computed(() => immediateBalance.value)

const changeColorClass = computed(() => {
  return dayChange.value > 0 ? 'positive' : dayChange.value < 0 ? 'negative' : 'neutral'
})

const changeIcon = computed(() => {
  return dayChange.value > 0 ? '▲' : dayChange.value < 0 ? '▼' : '='
})

const nearPriceChangeClass = computed(() => {
  return nearPriceChange.value > 0 ? 'positive' : nearPriceChange.value < 0 ? 'negative' : 'neutral'
})

// 分离的数据更新函数
const updatePriceData = async () => {
  isPriceLoading.value = true
  try {
    // 从后端API获取NEAR价格（使用CoinMarketCap数据）
    const response = await walletApiService.getNearAsset()
    if (response) {
      nearPrice.value = response.priceKRW
      nearPriceChange.value = response.change24h
      nearPriceChangeRate.value = response.changeRate24h
      priceDataAvailable.value = true
    }
  } catch (error) {
    console.error('가격 데이터 업데이트 실패:', error)
    priceDataAvailable.value = false
  } finally {
    isPriceLoading.value = false
  }
}

const updateWalletData = async () => {
  isWalletLoading.value = true
  try {
    const walletData = await walletApiService.getWalletBalance()
    totalBalance.value = walletData.availableBalance
    immediateBalance.value = walletData.immediateBalance ?? walletData.availableBalance
    frozenBalance.value = walletData.frozenBalance ?? 0
    dayChange.value = walletData.dayChange
    dayChangeRate.value = walletData.dayChangeRate
    ledgerNearBalance.value = walletData.nearBalance
    freeHoldingNear.value = walletData.freeHoldingNear || 0
    nearStaked.value = walletData.nearStaked
    totalRewardsNear.value = walletData.totalRewardsNear || walletData.cumulativeRewardsNear || 0
    totalRewardsValue.value = walletData.totalRewardsValue || walletData.cumulativeRewardsValue || 0
    cumulativeRewardsNear.value = totalRewardsNear.value
    cumulativeRewardsValue.value = totalRewardsValue.value
    walletDataAvailable.value = true
  } catch (error) {
    console.error('지갑 데이터 업데이트 실패:', error)
    walletDataAvailable.value = false
  } finally {
    isWalletLoading.value = false
  }
}

const updateAssetData = async () => {
  isAssetLoading.value = true
  try {
    const nearAsset = await walletApiService.getNearAsset()
    // 这里可以根据需要更新其他资产相关数据
    assetDataAvailable.value = true
  } catch (error) {
    console.error('자산 데이터 업데이트 실패:', error)
    assetDataAvailable.value = false
  } finally {
    isAssetLoading.value = false
  }
}

const updateAllData = async () => {
  // 并行执行，但各自独立处理错误
  await Promise.allSettled([
    updatePriceData(),
    updateWalletData(),
    updateAssetData()
  ])
}

const refreshData = async () => {
  if (isLoading.value) return

  isLoading.value = true
  await updateAllData()

  setTimeout(() => {
    isLoading.value = false
  }, 1000)
}

const startPriceUpdates = () => {
  // 每30秒更新一次所有数据
  priceUpdateInterval = window.setInterval(updateAllData, 30000)
}

const stopPriceUpdates = () => {
  if (priceUpdateInterval) {
    clearInterval(priceUpdateInterval)
    priceUpdateInterval = null
  }
}

// 快捷操作函数
const handleDeposit = () => {
  router.push('/app/deposit')
}

const handleWithdraw = () => {
  router.push('/app/withdraw')
}

onMounted(async () => {
  await updateAllData()
  startPriceUpdates()
})

onUnmounted(() => {
  stopPriceUpdates()
})
</script>

<style scoped lang="scss">
.price-display {
  .currency-section {
    display: flex;
    flex-direction: column;
    gap: 24px;
  }

  .main-balance {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 20px;
    padding: 32px;
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
    border: none;
    text-align: center;
    color: white;

    .balance-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .balance-title {
        font-size: 16px;
        color: rgba(255, 255, 255, 0.9);
        margin: 0;
        font-weight: 500;
      }

      .balance-refresh {
        cursor: pointer;
        padding: 8px;
        border-radius: 8px;
        transition: background 0.2s ease;

        &:hover {
          background: rgba(255, 255, 255, 0.1);
        }

        .el-icon {
          color: rgba(255, 255, 255, 0.9);
          font-size: 16px;
          transition: transform 0.5s ease;

          &.rotate {
            transform: rotate(360deg);
          }
        }
      }
    }

    .balance-amount {
      margin-bottom: 12px;

      .currency-symbol {
        font-size: 28px; // C需求: 增大字体 (24px + 4px)
        color: rgba(255, 255, 255, 0.8);
        margin-right: 4px;
      }

      .amount {
        font-size: 54px; // C需求: 增大字体 (48px + 6px)
        font-weight: 700;
        color: white;
        line-height: 1;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
    }

    .balance-change {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      font-size: 16px;
      font-weight: 600;

      &.positive {
        color: #86efac;
      }

      &.negative {
        color: #fca5a5;
      }

      &.neutral {
        color: rgba(255, 255, 255, 0.8);
      }

      .change-icon {
        font-size: 12px;
      }
    }

    .balance-error {
      display: flex;
      justify-content: center;
      margin-top: 8px;

      .retry-button {
        color: rgba(255, 255, 255, 0.8);
        font-size: 14px;

        &:hover {
          color: white;
        }
      }
    }

    .amount {
      &.loading {
        color: rgba(255, 255, 255, 0.7);
        font-size: 32px;
      }

      &.error {
        color: #fca5a5;
        font-size: 28px;
      }
    }

    .balance-actions {
      display: flex;
      gap: 12px;
      justify-content: flex-start;
      margin-top: 20px;
      padding-left: 8px;

      .action-button {
        flex: 0 0 auto;
        width: 140px;
        height: 44px;
        border-radius: 12px;
        font-size: 15px;
        font-weight: 600;
        border: 2px solid rgba(255, 255, 255, 0.3);
        background: rgba(255, 255, 255, 0.15);
        color: white;
        backdrop-filter: blur(10px);
        transition: all 0.3s ease;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 6px;

        &:hover {
          background: rgba(255, 255, 255, 0.25);
          border-color: rgba(255, 255, 255, 0.5);
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        &:active {
          transform: translateY(0);
        }

        svg {
          flex-shrink: 0;
        }

        span {
          white-space: nowrap;
        }
      }
    }
  }

  .near-protocol-section {
    background: white;
    border-radius: 20px;
    padding: 28px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.06);
    border: 1px solid #e2e8f0;

    .near-header {
      margin-bottom: 24px;

      .protocol-info {
        display: flex;
        align-items: flex-start;
        gap: 16px;

        .near-logo {
          flex-shrink: 0;
          margin-top: 2px;
        }

        .protocol-details {
          flex: 1;

          .protocol-title {
            font-size: 18px;
            font-weight: 700;
            color: #1a202c;
            margin: 0 0 8px 0;
          }

          .upbit-price {
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;

            .exchange-label {
              font-size: 13px;
              color: #64748b;
              font-weight: 500;
            }

            .price-value {
              font-size: 16px;
              font-weight: 700;
              color: #1a202c;
            }

            .price-change {
              font-size: 14px;
              font-weight: 600;
              padding: 2px 6px;
              border-radius: 4px;

              &.positive {
                color: #10b981;
                background: rgba(16, 185, 129, 0.1);
              }

              &.negative {
                color: #ef4444;
                background: rgba(239, 68, 68, 0.1);
              }

              &.neutral {
                color: #64748b;
                background: rgba(100, 116, 139, 0.1);
              }
            }

            .price-loading {
              font-size: 14px;
              color: #94a3b8;
              font-style: italic;
            }

            .price-error {
              font-size: 14px;
              color: #ef4444;
              font-weight: 500;
            }

            .live-indicator {
              display: flex;
              align-items: center;
              gap: 4px;
              margin-left: auto;

              .live-dot {
                width: 6px;
                height: 6px;
                border-radius: 50%;
                background: #10b981;
                animation: pulse 2s infinite;
              }

              .live-text {
                font-size: 11px;
                color: #10b981;
                font-weight: 600;
                text-transform: uppercase;
              }
            }
          }
        }
      }
    }

    .near-locked-details {
      .locked-summary {
        margin-bottom: 20px;

        .summary-item {
          background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
          border: 1px solid #bae6fd;
          border-radius: 12px;
          padding: 20px;

          &.main-locked {
            .item-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 8px;

              .item-title {
                font-size: 14px;
                color: #0369a1;
                font-weight: 600;
              }

              .item-amount {
                font-size: 16px;
                color: #0369a1;
                font-weight: 700;
              }
            }

            .item-value-krw {
              font-size: 24px;
              font-weight: 700;
              color: #0c4a6e;
              text-align: center;
            }
          }
        }
      }

      .locked-breakdown {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        gap: 12px;

        .breakdown-item {
          background: #f8fafc;
          border: 1px solid #e2e8f0;
          border-radius: 12px;
          padding: 18px;
          transition: transform 0.2s ease, box-shadow 0.2s ease;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          }

          &.locked {
            background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
            border-color: #f59e0b;
          }

          &.rewards {
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
            border-color: #22c55e;
          }

          .breakdown-label {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;

            .label-text {
              font-size: 13px;
              color: #374151;
              font-weight: 600;
            }

            .label-icon {
              font-size: 16px;
            }
          }

          .breakdown-values {
            display: flex;
            flex-direction: column;
            gap: 4px;

            .token-amount {
              font-size: 18px; // C需求: 增大字体 (16px + 2px)
              color: #1a202c;
              font-weight: 700;
            }

            .krw-amount {
              font-size: 14px; // C需求: 增大字体 (13px + 1px)
              color: #64748b;
              font-weight: 500;
            }
          }
        }
      }
    }
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

@media (max-width: 1024px) {
  .price-display {
    .main-balance {
      padding: 28px 22px;

      .balance-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
      }
    }

    .near-protocol-section {
      padding: 24px;

      .protocol-info {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;

        .live-indicator {
          margin-left: 0;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .price-display {
    .main-balance {
      padding: 24px 18px;

      .balance-amount {
        .amount {
          font-size: 36px;
        }
      }

      .balance-header {
        width: 100%;
        align-items: stretch;

        .balance-title {
          font-size: 15px;
        }

        .balance-refresh {
          align-self: flex-end;
        }
      }

      .balance-actions {
        margin-top: 16px;
        gap: 10px;

        .action-button {
          max-width: 160px;
          height: 48px;
          font-size: 16px;
        }
      }
    }

    .near-protocol-section {
      padding: 20px;

      .protocol-info {
        .protocol-details {
          width: 100%;

          .upbit-price {
            flex-direction: row;
            align-items: center;
            gap: 6px;
          }
        }
      }

      .near-locked-details {
        .locked-summary {
          .summary-item {
            padding: 18px;

            .item-header {
              flex-direction: column;
              align-items: flex-start;
              gap: 6px;
            }

            .item-value-krw {
              font-size: 20px;
            }
          }
        }

        .locked-breakdown {
          grid-template-columns: 1fr 1fr;
          gap: 12px;

          .breakdown-item {
            padding: 16px;

            &:last-child {
              grid-column: 1 / -1;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 520px) {
  .price-display {
    .main-balance {
      padding: 20px 16px;

      .balance-amount {
        .amount {
          font-size: 36px; // C需求: 调整后的小屏字体
        }
      }

      .balance-change {
        font-size: 14px;
      }

      .balance-actions {
        margin-top: 14px;
        gap: 8px;

        .action-button {
          max-width: none;
          height: 46px;
          font-size: 15px;
        }
      }
    }

    .near-protocol-section {
      padding: 18px;

      .protocol-info {
        align-items: stretch;

        .protocol-details {
          .protocol-title {
            font-size: 16px;
          }

          .upbit-price {
            flex-direction: column;
            align-items: flex-start;
            gap: 6px;

            .live-indicator {
              margin-top: 6px;
            }
          }
        }
      }

      .near-locked-details {
        .locked-summary {
          .summary-item {
            padding: 16px;
          }
        }

        .locked-breakdown {
          grid-template-columns: 1fr;

          .breakdown-item {
            &:last-child {
              grid-column: auto;
            }
          }
        }
      }
    }
  }
}
</style>
